package com.uinnova.product.eam.service.es;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.model.vo.ESRltSearchBeanVO;
import com.uinnova.product.vmdb.comm.model.rlt.CCcCiRlt;
import com.uinnova.product.vmdb.provider.rlt.bean.CcCiRltInfo;
import com.uino.bean.cmdb.base.ESCIRltInfo;
import com.uino.bean.cmdb.base.VisualModelRltCiClassIds;
import com.uino.bean.cmdb.query.ESRltSearchBean;
import com.uino.dao.AbstractESBaseDao;
import com.uino.dao.ESConst;
import com.uino.dao.util.ESUtil;
import com.uino.service.cmdb.microservice.IVisualModelSvc;
import com.uino.util.sys.SysUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 私有库ci关系es
 * 
 * @author zhaoyujie
 *
 */
 @Repository
public class IamsESCIRltPirvateSvc extends AbstractESBaseDao<ESCIRltInfo, CCcCiRlt> {

    Log logger = LogFactory.getLog(IamsESCIRltPirvateSvc.class);

    @Autowired
    IamsESCmdbCommPrivateSvc commSvc;

    @Autowired
    private IamsCIRltPrivateNonComplianceDao iamsCIRltPrivateNonComplianceDao;

    @Autowired
    private IVisualModelSvc visualModelSvc;

    @Override
    public String getIndex() {
        return ESConst.INDEX_CMDB_RLT + "_private";
    }

    @Override
    public String getType() {
        return ESConst.INDEX_CMDB_RLT + "_private";
    }

    @PostConstruct
    public void init() {
        super.initIndex();
    }

    @Override
    public Long saveOrUpdate(ESCIRltInfo t) {
        savePreOption(t);
        JSONObject json = JSON.parseObject(JSON.toJSONString(t, new ValueFilter() {

            @Override
            public Object process(Object object, String name, Object value) {
                if (value == null) { return ""; }
                return value;
            }
        }));
        return super.saveOrUpdate(json, true);
    }

    /**
     * <b>根据cdt对象查询分类
     *
     * @param pageNum
     * @param pageSize
     * @param bean
     *            自动生成的分类查询对象
     * @return
     */
    public Page<CcCiRltInfo> searchRltByCdt(int pageNum, int pageSize, CCcCiRlt bean) {
        QueryBuilder query = ESUtil.cdtToBuilder(bean);
        Page<ESCIRltInfo> page = super.getSortListByQuery(pageNum, pageSize, query, "modifyTime", false);
        return commSvc.tranCcCiRltInfoPage(page);
    }

    /**
     * <b> 查询关系
     *
     * @param bean
     * @return
     */
    public Page<CcCiRltInfo> searchRltByBean(ESRltSearchBean bean) {
        return commSvc.tranCcCiRltInfoPage(this.searchESRltByBean(bean));
    }

    public Page<ESCIRltInfo> searchESRltByBean(ESRltSearchBean bean) {
        QueryBuilder query = commSvc.getRltQueryBuilderByBean(bean);
        List<SortBuilder<?>> sorts = new LinkedList<>();
        if (bean.getSortField().startsWith("attrs.")) {
            sorts.add(SortBuilders.fieldSort(bean.getSortField().concat(".keyword")).order(bean.getIsAsc() ? SortOrder.ASC : SortOrder.DESC));
        } else {
            sorts.add(SortBuilders.fieldSort(bean.getSortField()).order(bean.getIsAsc() ? SortOrder.ASC : SortOrder.DESC));
        }
        Page<ESCIRltInfo> page = super.getSortListByQuery(bean.getPageNum(), bean.getPageSize(), query, sorts);

        return page;
    }

    public Page<CcCiRltInfo> rltPageToFullPage(Page<ESCIRltInfo> rltPage) {
        return commSvc.tranCcCiRltInfoPage(rltPage);
    }

    /**
     * <b> 查询关系
     *
     * @param bean
     * @return
     */
    public List<CcCiRltInfo> searchRltByScroll(ESRltSearchBean bean) {
        return commSvc.tranCcCiRltInfoList(searchESRltByScroll(bean));
    }

    public List<ESCIRltInfo> searchESRltByScroll(ESRltSearchBean bean) {
        QueryBuilder query = commSvc.getRltQueryBuilderByBean(bean);
        List<SortBuilder<?>> sorts = new LinkedList<>();
        String sortField = bean.getSortField();
        if (bean.getSortField().startsWith("attrs.")) {
            String[] split = sortField.split("\\.");
            sortField = "attrs." + (split.length > 1 ? split[1] : sortField).toUpperCase() + ".keyword";
            long count = this.countByCondition(QueryBuilders.existsQuery(sortField));
            if (count <= 0) {
                sortField = "modifyTime";
            }
            sorts.add(SortBuilders.fieldSort(sortField).order(bean.getIsAsc() ? SortOrder.ASC : SortOrder.DESC));
        } else {
            sorts.add(SortBuilders.fieldSort(bean.getSortField()).order(bean.getIsAsc() ? SortOrder.ASC : SortOrder.DESC));
        }
        return super.getListByQueryScroll(query);
    }

    public Page<CcCiRltInfo> searchRltByBeanVO(ESRltSearchBeanVO bean) {
        return commSvc.tranCcCiRltInfoPage(this.searchESRltByBeanVO(bean));
    }

    private Page<ESCIRltInfo> searchESRltByBeanVO(ESRltSearchBeanVO bean) {
        BoolQueryBuilder query = (BoolQueryBuilder) commSvc.getRltQueryBuilderByBean(bean);
        if (StringUtils.isNotEmpty(bean.getGteTime())) {
            Long gteTime = convertTime(bean.getGteTime());
            query.must(QueryBuilders.rangeQuery("createTime").gte(gteTime));
        }
        if (StringUtils.isNotEmpty(bean.getLteTime())) {
            Long lteTime = convertEndTime(bean.getLteTime());
            query.must(QueryBuilders.rangeQuery("createTime").lte(lteTime));
        }
        List<SortBuilder<?>> sorts = new LinkedList<>();
        if (bean.getSortField().startsWith("attrs.")) {
            sorts.add(SortBuilders.fieldSort(bean.getSortField().concat(".keyword")).order(bean.getIsAsc() ? SortOrder.ASC : SortOrder.DESC));
        } else {
            sorts.add(SortBuilders.fieldSort(bean.getSortField()).order(bean.getIsAsc() ? SortOrder.ASC : SortOrder.DESC));
        }
        if (bean.getUsage() == 1) {
            Page<ESCIRltInfo> page = super.getSortListByQuery(bean.getPageNum(), bean.getPageSize(), query, sorts);
            return page;
        }else{
            //下面走私有库的不合规数据查询
            Page<ESCIRltInfo> page = iamsCIRltPrivateNonComplianceDao.getSortListByQuery(bean.getPageNum(), bean.getPageSize(), query, sorts);
            return page;
        }
    }

    private Long convertTime(String convertTime) {
        String replace = convertTime.replace("/", "")+"000000";
        return Long.valueOf(replace);
    }

    private Long convertEndTime(String lteTime) {
        String replace = lteTime.replace("/", "")+"240000";
        return Long.valueOf(replace);
    }

    public List<ESCIRltInfo> searchRltByBeanByCondition(ESRltSearchBeanVO reqBean) {
        return this.noPageQuery(reqBean);
    }

    private List<ESCIRltInfo> noPageQuery(ESRltSearchBeanVO bean) {
        if(bean.getCheckData()){
            Long domainId = SysUtil.getCurrentUserInfo().getDomainId();
            Long rltClassId = bean.getRltClassIds().get(0);
            VisualModelRltCiClassIds visualModelRltCiClassIds = visualModelSvc.queryEnableVisualModelRltSourceAndTarget(domainId, rltClassId);
            bean.setNotMathSourceClassIds(visualModelRltCiClassIds.getSourceClassIds());
            bean.setNotMatchTargetClassIds(visualModelRltCiClassIds.getTargetClassIds());
        }
        BoolQueryBuilder query = (BoolQueryBuilder) commSvc.getRltQueryBuilderByBean(bean);
        if (StringUtils.isNotEmpty(bean.getGteTime())) {
            Long gteTime = convertTime(bean.getGteTime());
            query.must(QueryBuilders.rangeQuery("createTime").gte(gteTime));
        }
        if (StringUtils.isNotEmpty(bean.getLteTime())) {
            Long lteTime = convertEndTime(bean.getLteTime());
            query.must(QueryBuilders.rangeQuery("createTime").lte(lteTime));
        }
        if (StringUtils.isNotBlank(bean.getOwnerCode())) {
            query.must(QueryBuilders.termQuery("ownerCode.keyword",bean.getOwnerCode()));
        }
        List<SortBuilder<?>> sorts = new LinkedList<>();
        if (bean.getSortField().startsWith("attrs.")) {
            sorts.add(SortBuilders.fieldSort(bean.getSortField().concat(".keyword")).order(bean.getIsAsc() ? SortOrder.ASC : SortOrder.DESC));
        } else {
            sorts.add(SortBuilders.fieldSort(bean.getSortField()).order(bean.getIsAsc() ? SortOrder.ASC : SortOrder.DESC));
        }
        if (bean.getUsage() == 1) {
            Page<ESCIRltInfo> page = super.getSortListByQuery(1, 3000, query, sorts);
            return  page !=null ? page.getData() : new ArrayList<>();
        }else{
            Page<ESCIRltInfo> page = iamsCIRltPrivateNonComplianceDao.getSortListByQuery(1, 3000, query, sorts);
            return  page !=null ? page.getData() : new ArrayList<>();
        }

    }
}
